#include<bits/stdc++.h>
using namespace std;
#define int long long

void solve(){
    int n;
    cin >> n;
    vector<int> p(n);
    for (int i = 0; i < n; i++){
        cin >> p[i];
        p[i]--;
    }

    set<int> X;
    for (int i = 0; i < n; i++){
        int d;
        cin >> d;
        d--;
        while(!X.contains(d)){
            X.insert(d);
            d = p[d];
        }
        cout << X.size() << ' ';
    } 
    cout << endl;
}
 
signed main()
{
    //freopen("9.in", "r", stdin);
    //freopen("9.out", "w", stdout);
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int t;
	cin >> t;
	while(t--){
	    solve();
	}
}